package com.sinosoft.msf.base.supplier.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sinosoft.msf.base.supplier.dao.base.SCompanyInfoMapper;
import com.sinosoft.msf.base.supplier.dao.base.SEvaluateRecordMapper;
import com.sinosoft.msf.base.supplier.dao.base.SProjectCompanyMapper;
import com.sinosoft.msf.base.supplier.dao.base.SProjectMapper;
import com.sinosoft.msf.base.supplier.expection.BizException;
import com.sinosoft.msf.base.supplier.pojo.AppraisePojo;
import com.sinosoft.msf.base.supplier.pojo.OptVo;
import com.sinosoft.msf.base.supplier.pojo.PageParamVo;
import com.sinosoft.msf.base.supplier.pojo.entity.SCompanyInfo;
import com.sinosoft.msf.base.supplier.pojo.entity.SEvaluateRecord;
import com.sinosoft.msf.base.supplier.pojo.entity.SProjectCompany;
import com.sinosoft.msf.base.supplier.pojo.entity.SProjectInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
@Slf4j
@Service
public class CompanyAppraiseService {
    @Autowired
    ProjectService projectService;
    @Autowired
    SCompanyInfoMapper companyInfoMapper;
    @Autowired
    SEvaluateRecordMapper recordMapper;
    @Autowired
    SProjectMapper projectMapper;
    @Autowired
    SProjectCompanyMapper projectCompanyMapper;
    public AppraisePojo detail(AppraisePojo appraisePojo,OptVo optVo) {
        SProjectInfo sProjectInfo = projectService.queryProjectById(appraisePojo.getProjectId());
        SCompanyInfo sCompanyInfo = companyInfoMapper.selectByPrimaryKey(appraisePojo.getCompanyId());
        SProjectCompany queryModel = new SProjectCompany();
        queryModel.setProjectId(appraisePojo.getProjectId());
        queryModel.setCompanyId(appraisePojo.getCompanyId());
        queryModel.setDeleted("n");
        List<SProjectCompany> selectCom = projectCompanyMapper.select(queryModel);
        if (CollUtil.isNotEmpty(selectCom)) {
            appraisePojo.setSelected(selectCom.get(0).getStatus());
        }
        Example exp = new Example(SEvaluateRecord.class, true, true);
        exp.createCriteria().andEqualTo("projectId", appraisePojo.getProjectId())
                .andEqualTo("companyId", appraisePojo.getCompanyId())
                .andEqualTo("deleted", "n");
        List<SEvaluateRecord> recordList = recordMapper.selectByExample(exp);
        for (SEvaluateRecord sEvaluateRecord : recordList) {
            sEvaluateRecord.setUserId(optVo.getUserId());
        }
        Function<SEvaluateRecord, String> grenKey = a -> DateUtil.formatDateTime(a.getCreatedDate()) +" "+ StrUtil.emptyToDefault(a.getUserDept(),"--") +" "+ a.getUserName();
        Map<String, List<SEvaluateRecord>> collect = recordList.stream().collect(Collectors.groupingBy(grenKey::apply));
        appraisePojo.setProjectInfo(sProjectInfo);
        appraisePojo.setCompanyInfo(sCompanyInfo);
        appraisePojo.setRecordHis(collect);
        appraisePojo.setSameUser(sProjectInfo.getCreatedId().equals(optVo.getUserId())?"y":"n");
//        appraisePojo.setNeedSign(sProjectInfo.getNeedSign());
//        appraisePojo.setDoneSign(sProjectInfo.getDoneSign());
        return appraisePojo;
    }

    public void save(AppraisePojo appraisePojo, OptVo optVo) {
        SProjectInfo sProjectInfo = projectService.queryProjectById(appraisePojo.getProjectId());
        if (Objects.equals(optVo.getUserId(),sProjectInfo.getCreatedId())) {
            SProjectInfo projectInfo = appraisePojo.getProjectInfo();
            sProjectInfo.setNeedSign(projectInfo.getNeedSign());
            sProjectInfo.setDoneSign(projectInfo.getDoneSign());
            projectService.updateProject(sProjectInfo);
        }
        DecimalFormat df = new DecimalFormat("0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        List<SEvaluateRecord> records = appraisePojo.getRecords();
        DateTime now = DateUtil.date();
        for (SEvaluateRecord record : records) {
            String afterFmt = null;
            try {
                BigDecimal org = new BigDecimal(record.getScore());
                afterFmt = df.format(org);
            } catch (Exception e) {
                throw new BizException("评价分数不正确，请重新填写");
            }
            record.setScore(afterFmt);
            record.setId(IdUtil.simpleUUID());
            record.setCompanyId(appraisePojo.getCompanyId());
            record.setProjectId(appraisePojo.getProjectId());
            record.setUserId(optVo.getUserId());
            record.setUserName(optVo.getUserName());
            record.setUserDept(optVo.getDeptName());
            record.setDeleted("n");
            record.setCreatedId(optVo.getUserId());
            record.setCreatedDate(now);
        }
        recordMapper.insertList(records);
    }

    public Page<JSONObject> query(PageParamVo paramVo, OptVo optVo) {
        PageHelper.startPage(paramVo.getPageNo(), paramVo.getPageSize());
        Page<JSONObject> maps = (Page<JSONObject>) projectMapper.queryAppraise(paramVo.getParamData());
        if (CollUtil.isNotEmpty(maps)) {
            for (JSONObject map : maps) {
                try {
                    String createdId = map.getString("createdid");
                    if (optVo.getUserId().equals(createdId)) {
                        map.put("self", "y");
                    }else{
                        map.put("self", "n");
                    }
                    Date createdDate = map.getDate("createddate");
                    map.put("createdDateStr", DateUtil.formatDateTime(createdDate));
                } catch (Exception e) {
                    log.error("日期转换错误",e);
                }
            }
        }
        return maps;
    }

    public void del(AppraisePojo appraisePojo,OptVo optVo) {
        SEvaluateRecord sEvaluateRecord = recordMapper.selectByPrimaryKey(appraisePojo.getRecordId());
        Validator.validateNotNull(sEvaluateRecord, "评论信息不存在");
        if (Objects.equals(sEvaluateRecord.getUserId(),optVo.getUserId())) {
            sEvaluateRecord.setDeleted("y");
            recordMapper.updateByPrimaryKeySelective(sEvaluateRecord);
        }else{
            throw new BizException("无权限删除该评论");
        }

    }
}
